package com.ruoyi.factory.bom.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factory.bom.domain.*;
import com.ruoyi.factory.bom.mapper.*;
import com.ruoyi.factory.bom.service.IDataHandleService;
import com.ruoyi.factory.common.domain.AjaxBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * @ClassName DataHandleServiceImpl
 * @Description: TODO
 * @Author LiuJiaji
 * @Date 2022/10/24 15:07
 **/
@Service
public class DataHandleServiceImpl implements IDataHandleService {

    @Value("${bomdata.sqlServer.sqlServerUrl}")
    private String url;

    @Value("${bomdata.sqlServer.userName}")
    private String username;

    @Value("${bomdata.sqlServer.passWord}")
    private String password;


    @Autowired
    private ProductCostMapper productCostMapper;

    @Autowired
    private MaterialCostMapper materialCostMapper;

    @Autowired
    private BomDataMapper bomDataMapper;

    @Autowired
    private BomCostMapper bomCostMapper;

    @Autowired
    private BomPriceMapper bomPriceMapper;

    private Connection conn;
    private PreparedStatement sql;
    private ResultSet rs;

    public AjaxBean dataTransfer(){

        //同步bom数据
        List<BomData> bomData = findBomData();
        //同步oracle价格
        findBomPrice();
        //分发产品
        ditrbtcp();
        //分发原料
        ditrbtyl();
        //分发到bom成本表
        ditrbt();

        return null;
    }

    public void findBomPrice(){
        bomPriceMapper.deleteBomPriceAll();
        // 定义oracle数据库的驱动的类
        String driverClass = "oracle.jdbc.OracleDriver";
        // 定义连接的oracle的url
        String url = "jdbc:oracle:thin:@61.163.50.132:1521:orcl";
        // 用户名
        String username = "sj0731";
        // 密码
        String password = "sj0731";

        // 定义Connection连接
        Connection conn = null;
        // 定义数据库的sql执行对象
        Statement stmt = null;

        // 定义查询结果的ResultSet对象
        ResultSet rs = null;

        PreparedStatement pst = null;

        ResultSet rst = null;


        //1存放原料 2存放价格
        List<BomPrice> bomInfoList1 = new ArrayList<>();
        List<BomPrice> bomInfoList2 = new ArrayList<>();
        try {
            // 注册数据库的驱动程序
            Class.forName(driverClass);
            // 获得数据库的连接
            conn = DriverManager.getConnection(url, username, password);
            // 创建sql执行对象
            stmt = conn.createStatement();
            String sql = "select  * from BD_MATERIAL_V ";
            pst = conn.prepareStatement(sql);
            rst = pst.executeQuery();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //封装
            while (rst.next()) {
                BomPrice bp = new BomPrice();
                bp.setCode(rst.getString("CODE"));
                String creationtime = rst.getString("CREATIONTIME");
                bp.setCreationtime(sdf.parse(creationtime));
                bp.setCreator(rst.getString("CREATOR"));
                bp.setDataoriginflag(rst.getString("DATAORIGINFLAG"));
                bp.setDiscountflag( rst.getString("DISCOUNTFLAG"));
                bp.setDr(rst.getString("DR"));
                bp.setElectronicsale(rst.getString("ELECTRONICSALE"));
                bp.setEnablestate(rst.getString("ENABLESTATE"));
                bp.setFee(rst.getString("FEE"));
                bp.setIntolerance(rst.getString("INTOLERANCE"));
                bp.setIselectrans(rst.getString("ISELECTRANS"));
                bp.setIsfeature(rst.getString("ISFEATURE"));
                bp.setIshproitems(rst.getString("ISHPROITEMS"));
                bp.setMaterialmnecode(rst.getString("MATERIALMNECODE"));
                bp.setMaterialspec(rst.getString("MATERIALSPEC"));
                String modifiedtime = rst.getString("MODIFIEDTIME");
                if(StringUtils.isNotEmpty(modifiedtime)){
                    bp.setModifiedtime(sdf.parse(modifiedtime));
                }
                bp.setModifier(rst.getString("MODIFIER"));
                bp.setName(rst.getString("NAME"));
                bp.setOutcloselowerlimit(rst.getString("OUTCLOSELOWERLIMIT"));
                bp.setOuttolerance(rst.getString("OUTTOLERANCE"));
                bp.setPkGroup(rst.getString("PK_GROUP"));
                bp.setPkMarbasclass(rst.getString("PK_MARBASCLASS"));
                bp.setPkMaterial(rst.getString("PK_MATERIAL"));
                bp.setPkMattaxes(rst.getString("PK_MATTAXES"));
                bp.setPkMeasdoc(rst.getString("PK_MEASDOC"));
                bp.setPkOrg(rst.getString("PK_ORG"));
                bp.setPkSource(rst.getString("PK_SOURCE"));
                bp.setProductfamily(rst.getString("PRODUCTFAMILY"));
                bp.setRetail(rst.getString("RETAIL"));
                bp.setSetpartsflag(rst.getString("SETPARTSFLAG"));
                String ts = rst.getString("TS");
                bp.setTs(sdf.parse(ts));
                bp.setUnitvolume(rst.getString("UNITVOLUME"));
                bp.setUnitweight(rst.getString("UNITWEIGHT"));
                bp.setVersion(rst.getString("VERSION"));
                bomInfoList1.add(bp);
            }
            // 执行查询
            //定义sql 查询语句
            String querysql = "select * from po_invoice_b";

            pst = conn.prepareStatement(querysql);
            rs = pst.executeQuery();
            //通过列名来获取数据
            while (rs.next()) {
                BomPrice bp = new BomPrice();
//                bp.setCsaleorgid(rs.getString("CSALEORGID"));
                String pk_material = rs.getString("PK_MATERIAL");
                bp.setCinventoryid(pk_material); //主键用于对比
                String caccountperiod = rs.getString("DSOURCEDATE"); //时间
                Date parse = new Date();
                if(StringUtils.isNotEmpty(caccountperiod)){
                    parse = sdf.parse(caccountperiod);
                }
                bp.setCaccountperiod(parse);
                String nprice = rs.getString("NORIGPRICE");//价格不含税
                if(StringUtils.isNotEmpty(nprice)){
                    bp.setNprice(new BigDecimal(nprice));
                }
                bomInfoList2.add(bp);
            }
            // 获取原料
            for (BomPrice bomPrice : bomInfoList1) {
                for (BomPrice price : bomInfoList2) {
                    String pkMaterial = bomPrice.getPkMaterial();
                    if(pkMaterial.equals(price.getCinventoryid())){
//                        bomPrice.setCsaleorgid(price.getCsaleorgid());
                        bomPrice.setCinventoryid(price.getCinventoryid());
                        bomPrice.setCaccountperiod(price.getCaccountperiod());
                        bomPrice.setNprice(price.getNprice());
                        bomPriceMapper.insertBomPrice(bomPrice);
                    }
                }
            }

            if(pst != null){
                pst.close();
            }
            if(rst != null){
                rst.close();
            }
            if (rs != null)
            {
                rs.close();
            }
            if (stmt != null)
            {
                stmt.close();
            }
            if (conn != null)
            {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @author: Liujiaji
     * @date: 2022/10/24 15:22
     * @description: TODO 查询bom原始数据
     * @param: []
     * @return: java.util.List<com.ruoyi.factory.bom.domain.BomData>
     **/
    public List<BomData> findBomData(){
        List<BomData> bomDataList = new ArrayList<>();

        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            // 连接数据库
            conn = DriverManager.getConnection(url, username, password);
//               sql = conn.prepareStatement("select * from BOM_016 where 身份证号 = ? ORDER BY 报告日期 DESC");
            sql = conn.prepareStatement("select * from BOM_016");
//               sql.setString(1, userIdCard);
            //执行查询语句
            rs = sql.executeQuery();
            List<String> columns = new ArrayList<>();
            for (int i = 1; i < rs.getMetaData().getColumnCount(); i++) {
                columns.add(rs.getMetaData().getColumnName(i));
            }
            while (rs.next()) {
                BomData bomData = new BomData();
                bomData.setBomname(rs.getString("BOMNAME"));
                bomData.setBomvar(rs.getString("BOMVAR"));
                bomData.setSeqnum(rs.getString("SEQNUM"));
                bomData.setParentid(rs.getString("PARENTID"));
                bomData.setFatherpartvar(rs.getString("FATHERPARTVAR"));
                bomData.setPartid(rs.getString("PARTID"));
                bomData.setNodeExistMode(rs.getString("NODE_EXIST_MODE"));
                bomData.setAssemblelevel(rs.getString("ASSEMBLELEVEL"));
                bomData.setPartvar(rs.getString("PARTVAR"));
                bomData.setSupplystate(rs.getString("SUPPLYSTATE"));
                bomData.setCounts(rs.getString("COUNTS"));
                bomData.setAssembleproctime(rs.getString("ASSEMBLEPROCTIME"));
                bomData.setVirtualpart(rs.getString("VIRTUALPART"));
                bomData.setValidtime(rs.getString("VALIDTIME"));
                bomData.setInvalidtime(rs.getString("INVALIDTIME"));
                bomData.setIsreference(rs.getString("ISREFERENCE"));
                bomData.setOperation(rs.getString("OPERATION"));
                bomData.setFrezonbombackup2(rs.getString("FREZONBOMBACKUP2"));
                bomData.setFrezonbombackup3(rs.getString("FREZONBOMBACKUP3"));
                bomData.setChinaname(rs.getString("CHINANAME"));
                bomData.setTotalweight(rs.getString("TOTALWEIGHT"));
                bomData.setAutostat(rs.getString("AUTOSTAT"));
                bomData.setNodeExistMode1(rs.getString("NODE_EXIST_MODE"));
                bomData.setNodetimestamp(rs.getString("NODETIMESTAMP"));
                bomDataList.add(bomData);
            }
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (sql != null) {
                sql.close();
                sql = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bomDataList;
    }


    /**
     * @author: Liujiaji
     * @date: 2022/10/24 16:05
     * @description: TODO 分发原始数据到原料和产品
     * @param: [bomData]
     * @return: com.ruoyi.factory.common.domain.AjaxBean
     **/
    public void ditrbt(){
        bomCostMapper.deleteBomCostAll();
        //找到root的产品并去重
        BomData bdp = new BomData();
        bdp.setParentid("root");
        List<BomData> bomData = bomDataMapper.selectBomDataList(bdp);
        Set<String> set = new HashSet<>();
        for (BomData bomDatum : bomData) {
            set.add(bomDatum.getPartid());
        }
        //取值并找到最高版本
        for (String s : set) {
            bdp.setPartid(s);
            List<BomData> bomData1 = bomDataMapper.selectBomDataListOrder(bdp);
            BomData bomDatum = bomData1.get(0);

            BomCost bc = new BomCost();

            bc.setRootCode(s);
            bc.setId(UUID.randomUUID().toString());
            bc.setChinaName(bomDatum.getChinaname());
            bc.setBomName(bomDatum.getBomname());
            bc.setBomVar(bomDatum.getBomvar());
            bc.setParentId(bomDatum.getParentid());
            bc.setFatherPartvar(bomDatum.getFatherpartvar());
            bc.setPartId(bomDatum.getPartid());
            bc.setAssembLelevel(bomDatum.getAssemblelevel());
            bc.setPartVar(bomDatum.getPartvar());
            bc.setCounts(bomDatum.getCounts());
            //处理时间格式
            String nodetimestamp = bomDatum.getNodetimestamp();
            if (StringUtils.isNotEmpty(nodetimestamp)) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    Date parse = sdf.parse(nodetimestamp);
                    bc.setNodeTimesTamp(parse);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String partId = bc.getPartId();

                ProductCost pc = new ProductCost();
                pc.setPartId(partId);
                List<ProductCost> productCosts = productCostMapper.selectProductCostList(pc);
                if (!productCosts.isEmpty()) {
                    ProductCost productCost = productCosts.get(0);
                    if (StringUtils.isNotEmpty(productCost.getAsName())) {
                        bc.setAsName(productCost.getAsName());
                    }
                    if (StringUtils.isNotEmpty(productCost.getYear())) {
                        bc.setYear(productCost.getYear());
                    }
                    if (StringUtils.isNotEmpty(productCost.getAsName())) {
                        bc.setAsName(productCost.getAsName());
                    }
                    if (null != productCost.getGrossProfitRate() && productCost.getGrossProfitRate().compareTo(new BigDecimal("0")) != 0) {
                        bc.setGrossProfitRate(productCost.getGrossProfitRate());
                    }else{
                        bc.setGrossProfitRate(new BigDecimal("0"));
                    }
                    bc.setType("1");
                    //产品
                    BigDecimal bigDecimal1 = new BigDecimal("0.00");
                    BigDecimal bigDecimal2 = new BigDecimal("0.00");
                    if(null != productCost.getWorkFee() && (productCost.getWorkFee().compareTo(new BigDecimal("0")) !=0)){
                        bigDecimal1 = bigDecimal1.add(productCost.getWorkFee());
                        bc.setWorkFee(productCost.getWorkFee());
                    }
                    if(null != productCost.getGasFee() && (productCost.getGasFee().compareTo(new BigDecimal("0")) !=0)){
                        bigDecimal1 = bigDecimal1.add(productCost.getGasFee());
                        bc.setGasFee(productCost.getGasFee());
                    }
                    if(null != productCost.getElecFee() && (productCost.getElecFee().compareTo(new BigDecimal("0")) !=0)){
                        bigDecimal1 = bigDecimal1.add(productCost.getElecFee());
                        bc.setElecFee(productCost.getElecFee());
                    }
                    if(null != productCost.getMakeFee() && (productCost.getMakeFee().compareTo(new BigDecimal("0")) !=0)){
                        bigDecimal1 = bigDecimal1.add(productCost.getMakeFee());
                        bc.setMakeFee(productCost.getMakeFee());
                    }
                    //查找子节点
                    Map<String, BigDecimal> stMap = addPrice(bc.getPartId(), bomDatum.getBomvar(), bc.getBomName(), bc.getRootCode());
                    BigDecimal st = stMap.get("st");
                    BigDecimal te = stMap.get("te");
                    bc.setMarktaxPrice(te);
                    bc.setTaxPrice(st);
                    bigDecimal2 = bigDecimal1;
                    bigDecimal1 = bigDecimal1.add(st);
                    bc.setStTotalFee(bigDecimal1.multiply(new BigDecimal(bomDatum.getCounts())));
                    bigDecimal2 = bigDecimal2.add(te);
                    bc.setTotalFee(bigDecimal2.multiply(new BigDecimal(bomDatum.getCounts())));

                    BigDecimal ml = bc.getGrossProfitRate().divide(new BigDecimal("100"));
                    BigDecimal ll = new BigDecimal("1").subtract(ml);
                    //成本除以毛利
                    BigDecimal divide = bc.getTotalFee().divide(ll, 3, BigDecimal.ROUND_HALF_UP);
                    BigDecimal divide1 = bc.getStTotalFee().divide(ll, 3, BigDecimal.ROUND_HALF_UP);
                    bc.setStSalePrice(divide1);
                    bc.setSalePrice(divide);
            }
            bomCostMapper.insertBomCost(bc);
        }
    }

    /**
     * @author: Liujiaji
     * @date: 2022/10/26 16:29
     * @description: TODO 循环找价格
     * @param: [partId, counts]
     * @return: java.math.BigDecimal
     **/
    public Map<String,BigDecimal> addPrice (String partId,String bomvar,String bomName, String rootCode) {
        //st为标准总价  te为预测总价
        Map<String,BigDecimal> resultMap= new HashMap<>();
        //标准
        BigDecimal bigDecimal1 = new BigDecimal("0.00");
        //测试
        BigDecimal bigDecimal2 = new BigDecimal("0.00");

        BomData bd = new BomData();
        bd.setParentid(partId);
        bd.setBomvar(bomvar);
        bd.setBomname(bomName);
        List<BomData> bomDatas = bomDataMapper.selectBomDataList2(bd);
        for (BomData bomData : bomDatas) {
            //判断是不是原料
            MaterialCost mc = new MaterialCost();
            mc.setPartId(bomData.getPartid());
            List<MaterialCost> materialCosts = materialCostMapper.selectMaterialCostList(mc);
            //如果不是空说明是原料 计算成本
            if (!materialCosts.isEmpty()) {
                //标准
                BigDecimal bigDecimal3 = new BigDecimal("0.00");
                //测试
                BigDecimal bigDecimal4 = new BigDecimal("0.00");
                //含税价*数量 判断到是原料,通过原料找到
                bd.setPartid(bomData.getPartid());
                List<BomData> bomData1 = bomDataMapper.selectBomDataList(bd);
                BomData bomData2 = bomData1.get(0);
                String counts = bomData2.getCounts();

                MaterialCost materialCost = materialCosts.get(0);
                BigDecimal marktaxPrice = materialCost.getMarktaxPrice();
                BigDecimal marketPrice = materialCost.getMarketPrice();
                BigDecimal taxPrice = materialCost.getTaxPrice();
                BigDecimal price = materialCost.getPrice();
                //市场价优先
                BomCost bc = new BomCost();

                if (null != price && (price.compareTo(new BigDecimal("0")) != 0)) {
                    bc.setPrice(price);
                }
                //含标准税
                if (null != taxPrice && (taxPrice.compareTo(new BigDecimal("0")) != 0)) {
                    bigDecimal3 = taxPrice.multiply(new BigDecimal(counts));
                    bigDecimal4 = taxPrice.multiply(new BigDecimal(counts));
                    bc.setTaxPrice(taxPrice);
                    bc.setStTotalFee(bigDecimal3);
                    bc.setTotalFee(bigDecimal4);
                }
                if (null != marketPrice && (marketPrice.compareTo(new BigDecimal("0")) != 0)) {
                    bc.setMarketPrice(marketPrice);
                }
                //市场含税
                if (null != marktaxPrice && (marktaxPrice.compareTo(new BigDecimal("0")) != 0)) {
                    bigDecimal4 = marktaxPrice.multiply(new BigDecimal(counts));
                    bc.setMarktaxPrice(marktaxPrice);
                    bc.setTotalFee(bigDecimal4);
                }
                bigDecimal1 = bigDecimal1.add(bigDecimal3);
                bigDecimal2 = bigDecimal2.add(bigDecimal4);
                if(null != materialCost.getAsName()){
                    bc.setAsName(materialCost.getAsName());
                }
//                BomCost bc = new BomCost();
                bc.setId(UUID.randomUUID().toString());
                bc.setChinaName(bomData.getChinaname());
//                bc.setBomName(bomData.getBomname());
                bc.setBomVar(bomData.getBomvar());
                bc.setParentId(bomData.getParentid());
                bc.setFatherPartvar(bomData.getFatherpartvar());
                bc.setPartId(bomData.getPartid());
                bc.setAssembLelevel(bomData.getAssemblelevel());
                bc.setPartVar(bomData.getPartvar());
                bc.setCounts(bomData.getCounts());
                bc.setType("0");
                bc.setBomName(bomName);
                bc.setRootCode(rootCode);
                bomCostMapper.insertBomCost(bc);
            }else{
                BigDecimal bigDecimal3 = new BigDecimal("0.00");
                BigDecimal bigDecimal4 = new BigDecimal("0.00");
                //产品计算成本
                ProductCost pc = new ProductCost();
                pc.setPartId(bomData.getPartid());
                List<ProductCost> productCosts = productCostMapper.selectProductCostList(pc);
                if(!productCosts.isEmpty()){
                    BomCost bc = new BomCost();
                    ProductCost productCost = productCosts.get(0);
                    //产品
                    if(null != productCost.getWorkFee() && (productCost.getWorkFee().compareTo(new BigDecimal("0")) !=0)){
                        bigDecimal3 = bigDecimal3.add(productCost.getWorkFee());
                        bc.setWorkFee(productCost.getWorkFee());
                    }
                    if(null != productCost.getGasFee() && (productCost.getGasFee().compareTo(new BigDecimal("0")) !=0)){
                        bigDecimal3 = bigDecimal3.add(productCost.getGasFee());
                        bc.setGasFee(productCost.getGasFee());
                    }
                    if(null != productCost.getElecFee() && (productCost.getElecFee().compareTo(new BigDecimal("0")) !=0)){
                        bigDecimal3 = bigDecimal3.add(productCost.getElecFee());
                        bc.setElecFee(productCost.getElecFee());
                    }
                    if(null != productCost.getMakeFee() && (productCost.getMakeFee().compareTo(new BigDecimal("0")) !=0)){
                        bigDecimal3 = bigDecimal3.add(productCost.getMakeFee());
                        bc.setMakeFee(productCost.getMakeFee());
                    }

                    Map<String, BigDecimal> addmap = addPrice(productCost.getPartId(), bomvar, bomName, rootCode);
                    BigDecimal te = addmap.get("te");
                    BigDecimal st = addmap.get("st");
                    bigDecimal4 = bigDecimal3.add(te);
                    bigDecimal3 = bigDecimal3.add(st);

                    bc.setTaxPrice(bigDecimal3);
                    bc.setMarktaxPrice(bigDecimal4);


//                    BomData bdp = new BomData();
//                    bdp.setPartid(productCost.getPartId());
//                    List<BomData> bomData1 = bomDataMapper.selectBomDataListOrder(bdp);
//                    BomData bomDatum = bomData1.get(0);

                    if(null != productCost.getAsName()){
                        bc.setAsName(productCost.getAsName());
                    }
                    bc.setId(UUID.randomUUID().toString());
                    bc.setChinaName(bomData.getChinaname());
//                    bc.setBomName(bomData.getBomname());
                    bc.setBomVar(bomData.getBomvar());
                    bc.setParentId(bomData.getParentid());
                    bc.setFatherPartvar(bomData.getFatherpartvar());
                    bc.setPartId(bomData.getPartid());
                    bc.setAssembLelevel(bomData.getAssemblelevel());
                    bc.setPartVar(bomData.getPartvar());
                    bc.setCounts(bomData.getCounts());
                    bc.setType("2");

                    //设置总价,总价为原料+人工*数量
                    bigDecimal3 = bigDecimal3.multiply(new BigDecimal(bomData.getCounts()));
                    bc.setStTotalFee(bigDecimal3);
                    bigDecimal1 = bigDecimal1.add(bigDecimal3);
                    bigDecimal4 = bigDecimal4.multiply(new BigDecimal(bomData.getCounts()));
                    bc.setTotalFee(bigDecimal4);
                    bigDecimal2 = bigDecimal2.add(bigDecimal4);
                    bc.setBomName(bomName);
                    bc.setRootCode(rootCode);
                    bomCostMapper.insertBomCost(bc);
                }
            }
        }
        resultMap.put("st",bigDecimal1);
        resultMap.put("te",bigDecimal2);
        return resultMap;
    }

    /**
     * @author: Liujiaji
     * @date: 2022/10/24 16:25
     * @description: TODO 分发到原料
     * @param: [mtrlcst]
     * @return: com.ruoyi.factory.common.domain.AjaxBean
     **/
    public void ditrbtyl(){

        //查询所有子数据去重
        List<BomData> bomData = bomDataMapper.selectBomDataList(new BomData());
        int i= 0;
        for (BomData bomDatum : bomData) {
            String partid = bomDatum.getPartid();
            //判断该物料是否是产品
            BomData bdp = new BomData();
            bdp.setParentid(partid);
            List<BomData> bomData1 = bomDataMapper.selectBomDataListDif(bdp);
            //不为空则是产品
            if(!bomData1.isEmpty()) continue;
            i ++;
            System.out.println("原料数量"+i);
            String partid1 = bomDatum.getPartid();
            MaterialCost mtrlcst = new MaterialCost();
            mtrlcst.setType("0");
            mtrlcst.setId(UUID.randomUUID().toString());
            mtrlcst.setCreateTime(DateUtils.getNowDate());
            mtrlcst.setPartId(partid1);
            mtrlcst.setChinaName(bomDatum.getChinaname());
            // 可能存在的问题,oracle没有维护物料和价格
            List<BomInfo> infoByCode = getInfoByCode(partid1);
            if(infoByCode.isEmpty()){
                //测试维护价格
                BigDecimal bigDecimal = new BigDecimal("1");
                BigDecimal multiply = bigDecimal.multiply(new BigDecimal("1.13"));
                mtrlcst.setPrice(bigDecimal);
                mtrlcst.setTaxPrice(multiply);

                MaterialCost mt = new MaterialCost();
                mt.setPartId(mtrlcst.getPartId());
                List<MaterialCost> mtcList = materialCostMapper.selectMaterialCostList(mt);
                if(!mtcList.isEmpty()) continue;
                materialCostMapper.insertMaterialCost(mtrlcst);
            }else{
                for (BomInfo bomInfo : infoByCode) {
                    //查询是否重复插入
                    mtrlcst.setId(UUID.randomUUID().toString());
                    MaterialCost mt = new MaterialCost();
                    mt.setPartId(mtrlcst.getPartId());
                    mt.setYear(bomInfo.getYear());
                    mt.setMoth(bomInfo.getMoth());
                    List<MaterialCost> mtcList = materialCostMapper.selectMaterialCostList(mt);
                    if(!mtcList.isEmpty()) continue;
                    mtrlcst.setPrice(bomInfo.getNprice());
                    mtrlcst.setYear(bomInfo.getYear());
                    mtrlcst.setMoth(bomInfo.getMoth());
                    mtrlcst.setPriceTime(bomInfo.getPriceTime());
                    BigDecimal nprice = bomInfo.getNprice();
                    if(null == nprice){
                        nprice = new BigDecimal("0");
                    }
                    mtrlcst.setTaxPrice(nprice.multiply(new BigDecimal("1.3")));
                    //查询是否存在,存在则返回,不存在则插入
                    materialCostMapper.insertMaterialCost(mtrlcst);
                }
            }

        }
        System.out.println("原料总数量---------------"+i);
        //查询oracle数据库获取价格设置单价
       /* List<BomInfo> infoByCode = getInfoByCode(mtrlcst.getPartId());
        for (BomInfo bomInfo : infoByCode) {
            //查询是否重复插入
            MaterialCost mt = new MaterialCost();
            mt.setPartId(mtrlcst.getPartId());
            mt.setYear(bomInfo.getYear());
            mt.setMoth(bomInfo.getMoth());
            List<MaterialCost> mtcList = materialCostMapper.selectMaterialCostList(mt);
            if(!mtcList.isEmpty()) return;
            mtrlcst.setType("0");
            mtrlcst.setPrice(bomInfo.getNprice());
            mtrlcst.setId(IdGen.uuid());
            mtrlcst.setYear(bomInfo.getYear());
            mtrlcst.setMoth(bomInfo.getMoth());
            mtrlcst.setCreateTime(DateUtils.getNowDate());
            //查询是否存在,存在则返回,不存在则插入
            materialCostMapper.insertMaterialCost(mtrlcst);
        }*/

    }

    /**
     * @author: Liujiaji
     * @date: 2022/10/24 16:27
     * @description: TODO 分发到产品
     * @param: [pdctcst]
     * @return: com.ruoyi.factory.common.domain.AjaxBean
     **/
    public void ditrbtcp(){
        //查产品去重
        List<BomData> bomData = bomDataMapper.selectBomDataList(new BomData());
        int i= 0;
        for (BomData bomDatum : bomData) {
            String parentid = bomDatum.getParentid();
            //如果为空或者为root则不计,直接返回
            if(StringUtils.isEmpty(parentid) || "root".equals(parentid)) continue;
            //根据产品id查询是否已经插入
            ProductCost param = new ProductCost();
            param.setPartId(parentid);
            List<ProductCost> productCosts = productCostMapper.selectProductCostList(param);
            if(productCosts.isEmpty()){
                ProductCost pdctcst = new ProductCost();
                pdctcst.setId(UUID.randomUUID().toString());
                pdctcst.setType("1");
                pdctcst.setCreateTime(DateUtils.getNowDate());
                pdctcst.setPartId(parentid);
                //查询bom元数据获取名字
                BomData param2 = new BomData();
                param2.setPartid(pdctcst.getPartId());
                List<BomData> bomData1 = bomDataMapper.selectBomDataListDiz(param2);
                for (BomData bomDatum2 : bomData1) {
                    pdctcst.setChinaName(bomDatum2.getChinaname());
                }
                //测试
                List<String> list = new ArrayList<>();
                for (int j = 0; j < 4; j++) {
//                    list.add(String.valueOf(Math.random() * 90 + 10));
                    list.add("1");
                }
                pdctcst.setWorkFee(new BigDecimal(list.get(0)));
                pdctcst.setGasFee(new BigDecimal(list.get(1)));
                pdctcst.setElecFee(new BigDecimal(list.get(2)));
                pdctcst.setMakeFee(new BigDecimal(list.get(3)));
                BigDecimal total = pdctcst.getWorkFee().add(pdctcst.getGasFee()).add(pdctcst.getElecFee()).add(pdctcst.getMakeFee()).add(pdctcst.getMakeFee());
                pdctcst.setTotalFee(total);
                i++;
                System.out.println("成品数量"+i);
                productCostMapper.insertProductCost(pdctcst);
            }
        }
        System.out.println("成品总数量------------"+i);
    }

    /**
     * @author: Liujiaji
     * @date: 2022/10/24 16:29
     * @description: TODO 分发到bom表
     * @param: [bomCost]
     * @return: com.ruoyi.factory.common.domain.AjaxBean
     **/
    public void ditrbtbcst(BomCost bomCost){

    }

    /**
     * @author: Liujiaji
     * @date: 2022/11/25 20:21
     * @description: TODO 根据code值获取该物料的详细信息
     * @param: [code]
     * @return: java.util.List<com.ruoyi.factory.bom.domain.BomInfo>
     **/
    public List<BomInfo> getInfoByCode(String code){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List<BomInfo> bomInfoList = new ArrayList<>();
        BomPrice bp = new BomPrice();
        bp.setCode(code);
        List<BomPrice> bomPrices = bomPriceMapper.selectBomPriceList(bp);
        String format = "";
        for (BomPrice bomPrice : bomPrices) {
            Date cadate = bomPrice.getCaccountperiod();
            BigDecimal nprice = bomPrice.getNprice();
            BomInfo bif = new BomInfo();
            bif.setChinaName(bomPrice.getName());
            bif.setNprice(nprice);
            String format2 = sdf.format(cadate);
            String[] split = format2.split("-");
            bif.setYear(split[0]);
            bif.setMoth(split[1]);
            bif.setPriceTime(cadate);
            if(!format2.equals(format)){
                format = format2;
                bomInfoList.add(bif);
            }
        }
        return bomInfoList;
    }


    /**
     * @author: Liujiaji
     * @date: 2022/10/24 20:40
     * @description: TODO 根据code值获取该物料的详细信息
     * @param: []
     * @return: java.util.Map<java.lang.String,java.lang.String>
     **/
    public List<BomInfo> getInfoByCode2(String code){

        // 定义oracle数据库的驱动的类
        String driverClass = "oracle.jdbc.OracleDriver";
        // 定义连接的oracle的url
        String url = "jdbc:oracle:thin:@61.163.50.132:1521:orcl";
        // 用户名
        String username = "sj0731";
        // 密码
        String password = "sj0731";

        // 定义Connection连接
        Connection conn = null;
        // 定义数据库的sql执行对象
        Statement stmt = null;

        // 定义查询结果的ResultSet对象
        ResultSet rs = null;

        PreparedStatement pst = null;

        ResultSet rst = null;
        //定义sql插入语句
        //String addsql = "insert into person(id,name,gender,birthday)values(personid.nextval,'李四','1',to_date('1996-09-23','yyyy-mm-dd'))";

        //定义sql 查询语句
        String querysql = "select pk_group,csaleorgid,cinventoryid,caccountperiod,nprice from (select tf.*,ROW_NUMBER() OVER(PARTITION BY  csaleorgid,cinventoryid ORDER BY caccountperiod DESC , pk_org ) RN from ia_i5bill_b tf where nprice is not null )  test where test .rn = 1 AND CINVENTORYID = ? ORDER BY CACCOUNTPERIOD DESC";

        String pk_material = null;
        String name = null;

        List<BomInfo> bomInfoList = new ArrayList<>();
        try {
            // 注册数据库的驱动程序
            Class.forName(driverClass);
            // 获得数据库的连接
            conn = DriverManager.getConnection(url, username, password);
            // 创建sql执行对象
            stmt = conn.createStatement();
            String sql = "select  * from BD_MATERIAL_V where CODE = ?";
            pst = conn.prepareStatement(sql);
            pst.setString(1,code);
            rst = pst.executeQuery();
            while (rst.next()) {
                pk_material = rst.getString("PK_MATERIAL");
                name = rst.getString("NAME");
            }
            // 执行查询
            pst = conn.prepareStatement(querysql);
            pst.setString(1,pk_material);
            rs = pst.executeQuery();
//            rs = stmt.executeQuery(querysql);

            //通过列名来获取数据
            while (rs.next()) {
                String date = rs.getString("CACCOUNTPERIOD");
                String nprice = rs.getString("NPRICE");
                BigDecimal bigDecimal = new BigDecimal(nprice);
                String[] split = date.split("-");
                BomInfo bif = new BomInfo();
                bif.setChinaName(name);
                bif.setNprice(bigDecimal);
                bif.setYear(split[0]);
                bif.setMoth(split[1]);
                if(StringUtils.isNotEmpty(date)){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    Date date1 = sdf.parse(date);
                    bif.setPriceTime(date1);
                }
//                bif.setPriceTime();
                bomInfoList.add(bif);
            }

            if(pst != null){
                pst.close();
            }
            if(rst != null){
                rst.close();
            }
            if (rs != null)
            {
                rs.close();
            }
            if (stmt != null)
            {
                stmt.close();
            }
            if (conn != null)
            {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bomInfoList;
    }

}
